package com.to.aboomy.bannersample.slice;

import com.to.aboomy.bannersample.ResourceTable;
import com.to.aboomy.bannersample.adapter.BannerAdapter;
import com.to.aboomy.bannersample.bean.BannerBean;
import com.to.aboomy.bannersample.bean.TextBean;
import com.to.aboomy.bannersample.util.Utils;
import com.to.aboomy.bannersample.util.loading.LoadingView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.multimodalinput.event.TouchEvent;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static ohos.multimodalinput.event.TouchEvent.*;

public class RecyclerAbilitySlice extends AbilitySlice implements Component.TouchEventListener{
    private ListContainer mRecyclerView;
    private Button update;
    BannerAdapter bannerAdapter;
    private LoadingView loadingView;
    private DirectionalLayout loading_view;
    private int widthPm;
    private Component root;
    /**
     * listContainer是否滑到顶部
     */
    private boolean isTop = true;
    private int scrolltop = 1;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_recycler);

        Optional<Display>
                display = DisplayManager.getInstance().getDefaultDisplay(this.getContext());
        DisplayAttributes displayAttributes = display.get().getAttributes();
        widthPm = displayAttributes.width;

        mRecyclerView = (ListContainer) findComponentById(ResourceTable.Id_xRecyclerView);
        mRecyclerView.setTouchEventListener(this);
        root = findComponentById(ResourceTable.Id_root);
        root.setTouchEventListener(this::onTouchEvent);
        update = (Button) findComponentById(ResourceTable.Id_update);
        loading_view = (DirectionalLayout) findComponentById(ResourceTable.Id_loading_view);
        loadingView = (LoadingView) findComponentById(ResourceTable.Id_progress_loading);
        loadingView.setBindStateChangedListener(loadingView);
        loadingView.setPaintcolor(Color.BLACK.getValue());
        loadingView.setSize(45);
        loadingView.stopAnimation();
        // 默认进度条的位置
        loading_view.setScaleX(0.2f);
        loading_view.setScaleY(0.2f);
        loading_view.setPosition(widthPm / 2 - 50, -100);

        bannerAdapter = new BannerAdapter(this);

        loadData(false);
        mRecyclerView.setItemProvider(bannerAdapter);

        update.setClickedListener(view -> {
            loadData(true);
            bannerAdapter.notifyDataChanged();
            initAddHeaderView();
        });

        mRecyclerView.addScrolledListener(new Component.ScrolledListener() {
            @Override
            public void onContentScrolled(Component component, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                isTop = scrollY == 0;
            }
        });

    }

    /**
     * 添加头部
     *
     * @return BannerBean
     */
    private BannerBean initAddHeaderView() {
        BannerBean bannerBean = new BannerBean();
        // 添加头部信息
        bannerBean.itemType = -1;
        bannerBean.urls = Utils.getImage(4);
        return bannerBean;
    }

    /**
     * 添加内容
     *
     * @param isNotify 是否是点击刷新
     */
    private void loadData(boolean isNotify){
        List<Object> list = new ArrayList<>();
        //添加头部数据
        list.add(initAddHeaderView());
        BannerBean bannerBean = new BannerBean();
        bannerBean.urls = new ArrayList<>();
        if (isNotify) {
            int i = new SecureRandom().nextInt(5);
            if (i == 0) {
                i = 3;
            }
            bannerBean.urls.addAll(Utils.getImage(i));
            list.add(bannerBean);
        } else {
            for (int i = 0; i < 5; i++) {
                bannerBean.urls.add(Utils.getRandomImage());
            }
            list.add(bannerBean);
        }
        for (int i = 0; i < 100; i++) {
            TextBean textBean = new TextBean();
            textBean.text = "--- " + i;
            list.add(textBean);
        }
        bannerAdapter.setData(list);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }



    private float downY;
    private float moveY;
    private float mOffsetY;

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        switch (touchEvent.getAction()) {
            case PRIMARY_POINT_DOWN:
                if (isTop && timeRecord()) {
                    downY = touchEvent.getPointerScreenPosition(0).getY();
                }
                return true;
            case POINT_MOVE:
                if (scrolltop == 1) {
                    if (timeRecord()) {
                        moveY = touchEvent.getPointerScreenPosition(touchEvent.getIndex()).getY();
                        mOffsetY = Math.min((moveY - downY), 700);
                        if (mOffsetY > 10 && isTop && (moveY - downY) < 700) {
                            if ((moveY - downY) <= 400) {
                                float scaleSize = mOffsetY / 500.0f;
                                if(scaleSize > 0.1f) {
                                    loading_view.setScaleX(scaleSize);
                                    loading_view.setScaleY(scaleSize);
                                } else {
                                    loading_view.setScaleX(0.2f);
                                    loading_view.setScaleY(0.2f);
                                }
                            } else {
                                loading_view.setScaleX(0.85f);
                                loading_view.setScaleY(0.85f);
                            }

                            mOffsetY = (moveY - downY);
                            loading_view.setPosition(widthPm / 2 - 50, (int) mOffsetY -50);
                            root.invalidate();
                        }
                    }
                }
                return true;
            case PRIMARY_POINT_UP:
                if (scrolltop == 1) {
                    if (timeRecord()) {
                        mOffsetY = Math.min((moveY - downY), 700);
                        if (mOffsetY < 400) {
                            AnimatorProperty animatorProperty = loading_view.createAnimatorProperty();
                            animatorProperty.setDuration(500).setDelay(100).scaleX(0).scaleY(0);
                            animatorProperty.start();

                            AnimatorProperty animatorProperty2 = loading_view.createAnimatorProperty();
                            animatorProperty2.moveFromY(mOffsetY).moveToY(-50).setDuration(500).setDelay(100);
                            animatorProperty2.start();

                        } else {
                            moveY = touchEvent.getPointerScreenPosition(touchEvent.getIndex()).getY();
                            loadingView.startAnimation();
                            animationFromTo(); //回退位置
                            // 设置 开始动画时间戳
                            lastClickTime = System.currentTimeMillis();
                            new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
                                @Override
                                public void run() {
                                    loadingView.stopAnimation();
                                    setTopHide();
                                    lastClickTime = 0;
                                }
                            }, 2000);
                            root.invalidate();
                            mOffsetY = 0;
                        }
                    }
                }
                return false;
        }
        return true;
    }

    /**
     * 设置隐藏
     */
    public void setTopHide() {
        AnimatorProperty animatorProperty = loading_view.createAnimatorProperty();
        animatorProperty.setDuration(500).setDelay(10).scaleX(0).scaleY(0);
        animatorProperty.start();
        new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
            @Override
            public void run() {
                animatorProperty.stop();
                loading_view.setPosition(widthPm / 2 - 50, -50);
                loadData(false);
                bannerAdapter.notifyDataChanged();
                initAddHeaderView();
                bannerAdapter.notifyDataChanged();
            }
        }, 500);
    }

    private AnimatorProperty animatorProperty;

    /**
     * animationFromTo
     */
    public void animationFromTo() {
        animatorProperty = loading_view.createAnimatorProperty();
        animatorProperty.moveFromY(mOffsetY).moveToY(200).setDuration(500).setDelay(100);
        animatorProperty.start();
    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private final int MIN_CLICK_DELAY_TIME = 2000;
    private long lastClickTime = 0;

    /**
     * timeRecord
     *
     * @return boolean
     */
    public boolean timeRecord() {
        if (lastClickTime == 0) {
            return true;
        }
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            // 超过点击间隔后再将lastClickTime重置为当前点击时间
            lastClickTime = curClickTime;
            return true;
        }
        return false;
    }
}
